package com.alan.sso.share.bean;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/20 18:00
 * @Description: PathPattern
 */
public class PathPattern {
    private static final String EXTENSION_MAPPING_PATTERN = "*.";
    private static final String PATH_MAPPING_PATTERN = "/*";
    private final List<String> exactMatches = new ArrayList();
    private final List<String> startsWithMatches = new ArrayList();
    private final List<String> endsWithMatches = new ArrayList();

    public PathPattern(String... urlPatterns) {
        String[] arr$ = urlPatterns;
        int len$ = urlPatterns.length;

        for(int i$ = 0; i$ < len$; ++i$) {
            String urlPattern = arr$[i$];
            this.addUrlPattern(urlPattern);
        }

    }

    private void addUrlPattern(String urlPattern) {
        if (urlPattern.startsWith("*.")) {
            this.endsWithMatches.add(urlPattern.substring(1, urlPattern.length()));
        } else if (urlPattern.equals("/*")) {
            this.startsWithMatches.add("");
        } else if (urlPattern.endsWith("/*")) {
            this.startsWithMatches.add(urlPattern.substring(0, urlPattern.length() - 1));
            this.exactMatches.add(urlPattern.substring(0, urlPattern.length() - 2));
        } else {
            if ("".equals(urlPattern)) {
                urlPattern = "/";
            }

            this.exactMatches.add(urlPattern);
        }

    }

    public boolean matches(HttpServletRequest request) {
        return this.matches(request.getRequestURI());
    }

    public boolean matches(String requestPath) {
        Iterator i$ = this.exactMatches.iterator();

        String pattern;
        do {
            if (!i$.hasNext()) {
                if (!requestPath.startsWith("/")) {
                    return false;
                }

                i$ = this.endsWithMatches.iterator();

                do {
                    if (!i$.hasNext()) {
                        i$ = this.startsWithMatches.iterator();

                        do {
                            if (!i$.hasNext()) {
                                return false;
                            }

                            pattern = (String)i$.next();
                        } while(!requestPath.startsWith(pattern));

                        return true;
                    }

                    pattern = (String)i$.next();
                } while(!requestPath.endsWith(pattern));

                return true;
            }

            pattern = (String)i$.next();
        } while(!pattern.equals(requestPath));

        return true;
    }
}
